package com.bw.mq;
import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSON;
import com.bw.domain.MyMessage;
import com.bw.service.ConsumerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
// 同一个消费者组的消费者， 按照队列的顺序消费，无法消费相同的内推
@RocketMQMessageListener(consumerGroup = "test", topic = "sms_topic")
@Slf4j
public class MyConsumer implements RocketMQListener<MyMessage> {

    @Autowired
    ConsumerService consumerService;

    @Autowired
    RedisTemplate redisTemplate;
    /**
     * 消费者 接收 消息
     *
     * @param message
     */
    @Override
    public void onMessage(MyMessage message) {
        try {
            // 防止重复消费
            String key = DigestUtil.md5Hex(JSON.toJSONString(message));
            Boolean b = redisTemplate.opsForValue().setIfAbsent(key, "1");
            if (!b){
                return;
            }
            consumerService.doMsg(message);  // 如果异常 执行3次
        } catch (Exception e) {
           log.error("-------消费者处理消息异常---{},,e{}",message,e);  // 如果3次都失败  异常并 打印
        }
    }
}
